<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生产线智能检测系统 - 登录</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            max-width: 900px;
            width: 90%;
        }
        .login-form {
            padding: 40px;
        }
        .login-image {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            padding: 40px;
        }
        .form-input {
            transition: all 0.3s ease;
        }
        .form-input:focus {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 122, 255, 0.2);
        }
        .btn-login {
            background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
            transition: all 0.3s ease;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 122, 255, 0.3);
        }
        .error-message {
            animation: shake 0.5s ease-in-out;
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
        }
        .loading-spinner {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="login-container grid md:grid-cols-2">
        <!-- 左侧图片区域 -->
        <div class="login-image">
            <div class="text-center">
                <div class="w-24 h-24 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-6">
                    <i class="fa fa-cogs text-4xl"></i>
                </div>
                <h1 class="text-3xl font-bold mb-4">生产线智能检测系统</h1>
                <p class="text-white/80 text-lg">智能化 · 高效率 · 安全可靠</p>
                <div class="mt-8 space-y-3 text-left">
                    <div class="flex items-center">
                        <i class="fa fa-check-circle mr-3"></i>
                        <span>实时故障监测</span>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-check-circle mr-3"></i>
                        <span>智能数据分析</span>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-check-circle mr-3"></i>
                        <span>生产可视化</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧登录表单 -->
        <div class="login-form">
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-gray-800 mb-2">欢迎回来</h2>
                <p class="text-gray-600">请登录您的账户以继续</p>
            </div>
            
            <form id="loginForm" class="space-y-6">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fa fa-user mr-1"></i>用户名
                    </label>
                    <input 
                        type="text" 
                        id="username" 
                        name="username"
                        class="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        placeholder="请输入用户名"
                        required
                    >
                    <span id="usernameError" class="text-red-500 text-sm mt-1 hidden">请输入用户名</span>
                </div>
                
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fa fa-lock mr-1"></i>密码
                    </label>
                    <div class="relative">
                        <input 
                            type="password" 
                            id="password" 
                            name="password"
                            class="form-input w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent pr-12"
                            placeholder="请输入密码"
                            required
                        >
                        <button 
                            type="button" 
                            id="togglePassword"
                            class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                        >
                            <i class="fa fa-eye"></i>
                        </button>
                    </div>
                    <span id="passwordError" class="text-red-500 text-sm mt-1 hidden">请输入密码</span>
                </div>
                
                <div class="flex items-center justify-between">
                    <label class="flex items-center">
                        <input type="checkbox" id="remember" class="mr-2 rounded">
                        <span class="text-sm text-gray-600">记住我</span>
                    </label>
                    <a href="#" class="text-sm text-blue-600 hover:text-blue-800">忘记密码？</a>
                </div>
                
                <button 
                    type="submit" 
                    id="loginBtn"
                    class="btn-login w-full text-white py-3 rounded-lg font-medium"
                >
                    <span id="loginText">登录</span>
                    <i id="loginSpinner" class="fa fa-circle-o-notch loading-spinner hidden ml-2"></i>
                </button>
                
                <div id="errorMessage" class="error-message bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg hidden">
                    <i class="fa fa-exclamation-circle mr-2"></i>
                    <span id="errorText"></span>
                </div>
            </form>
            
            <div class="mt-6 text-center">
                <p class="text-gray-600">
                    还没有账户？ 
                    <a href="#" class="text-blue-600 hover:text-blue-800 font-medium">联系管理员</a>
                </p>
            </div>
        </div>
    </div>

    <script>
        class LoginSystem {
            constructor() {
                this.init();
            }

            init() {
                this.bindEvents();
                this.loadRememberedUser();
            }

            bindEvents() {
                // 表单提交
                document.getElementById('loginForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleLogin();
                });

                // 密码显示/隐藏
                document.getElementById('togglePassword').addEventListener('click', () => {
                    this.togglePasswordVisibility();
                });

                // 输入框聚焦时隐藏错误提示
                ['username', 'password'].forEach(id => {
                    document.getElementById(id).addEventListener('focus', () => {
                        this.hideFieldError(id);
                    });
                });

                // 回车键登录
                document.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        this.handleLogin();
                    }
                });
            }

            async handleLogin() {
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value;
                const remember = document.getElementById('remember').checked;

                // 验证输入
                if (!this.validateInputs(username, password)) {
                    return;
                }

                // 显示加载状态
                this.setLoadingState(true);
                this.hideError();

                try {
                    const response = await fetch('/api/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            username: username,
                            password: password
                        })
                    });

                    const data = await response.json();

                    if (data.success) {
                        // 保存记住我状态
                        if (remember) {
                            localStorage.setItem('rememberedUsername', username);
                        } else {
                            localStorage.removeItem('rememberedUsername');
                        }

                        // 保存token
                        localStorage.setItem('authToken', data.token);
                        localStorage.setItem('userInfo', JSON.stringify(data.user));

                        // 登录成功，跳转到主系统
                        this.showSuccessMessage('登录成功，正在跳转...');
                        setTimeout(() => {
                            window.location.href = '/system';
                        }, 1000);
                    } else {
                        this.showError(data.message || '登录失败');
                    }
                } catch (error) {
                    console.error('登录请求失败:', error);
                    this.showError('网络连接失败，请检查网络后重试');
                } finally {
                    this.setLoadingState(false);
                }
            }

            validateInputs(username, password) {
                let isValid = true;

                if (!username) {
                    this.showFieldError('username', '请输入用户名');
                    isValid = false;
                }

                if (!password) {
                    this.showFieldError('password', '请输入密码');
                    isValid = false;
                }

                return isValid;
            }

            showFieldError(fieldId, message) {
                const field = document.getElementById(fieldId);
                const errorSpan = document.getElementById(fieldId + 'Error');
                
                field.classList.add('border-red-500');
                errorSpan.textContent = message;
                errorSpan.classList.remove('hidden');
            }

            hideFieldError(fieldId) {
                const field = document.getElementById(fieldId);
                const errorSpan = document.getElementById(fieldId + 'Error');
                
                field.classList.remove('border-red-500');
                errorSpan.classList.add('hidden');
            }

            showError(message) {
                const errorDiv = document.getElementById('errorMessage');
                const errorText = document.getElementById('errorText');
                
                errorText.textContent = message;
                errorDiv.classList.remove('hidden');
                
                // 添加动画效果
                errorDiv.classList.add('error-message');
                setTimeout(() => {
                    errorDiv.classList.remove('error-message');
                }, 500);
            }

            hideError() {
                document.getElementById('errorMessage').classList.add('hidden');
            }

            showSuccessMessage(message) {
                const errorDiv = document.getElementById('errorMessage');
                const errorText = document.getElementById('errorText');
                
                errorText.textContent = message;
                errorDiv.className = 'bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg';
                errorDiv.classList.remove('hidden');
            }

            setLoadingState(isLoading) {
                const loginBtn = document.getElementById('loginBtn');
                const loginText = document.getElementById('loginText');
                const loginSpinner = document.getElementById('loginSpinner');
                const inputs = document.querySelectorAll('input, button');

                if (isLoading) {
                    loginBtn.disabled = true;
                    loginText.textContent = '登录中...';
                    loginSpinner.classList.remove('hidden');
                    inputs.forEach(input => input.disabled = true);
                } else {
                    loginBtn.disabled = false;
                    loginText.textContent = '登录';
                    loginSpinner.classList.add('hidden');
                    inputs.forEach(input => input.disabled = false);
                }
            }

            togglePasswordVisibility() {
                const passwordInput = document.getElementById('password');
                const toggleBtn = document.getElementById('togglePassword');
                const icon = toggleBtn.querySelector('i');

                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    passwordInput.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            }

            loadRememberedUser() {
                const rememberedUsername = localStorage.getItem('rememberedUsername');
                if (rememberedUsername) {
                    document.getElementById('username').value = rememberedUsername;
                    document.getElementById('remember').checked = true;
                }
            }
        }

        // 初始化登录系统
        document.addEventListener('DOMContentLoaded', () => {
            new LoginSystem();
        });

        // 如果已登录，直接跳转
        if (localStorage.getItem('authToken')) {
            window.location.href = '/system';
        }
    </script>
</body>
</html>